package com.zhz.common.feign;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.zhz.common.tool.mybatisplus.base.core.contract.R;

import java.net.SocketTimeoutException;

/**
 * FeignFallbackResult
 * <p>
 * 当 feign 调用异常时，返回此经过包装的 Result
 *
 * @author zhouhengzhe
 */
public class FeignFallbackResult<T> extends R<T> {

    /**
     * 异常信息
     */
    private transient final Throwable cause;

    /**
     * 请求开始时间
     */
    private final long startTime;

    /**
     * 请求结束时间
     */
    private final long endTime;

    /**
     * 请求耗时
     */
    private final long interval;


    public FeignFallbackResult(String msg, Throwable cause, long startTime, long endTime) {
        this(R.fail().getCode(), msg, cause, startTime, endTime);
    }

    public FeignFallbackResult(int code, String msg, Throwable cause, long startTime, long endTime) {
        this.cause = cause;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = endTime - startTime;
        setCode(code);
        setMessage(msg);
    }


    /**
     * 注意：这里的方法名不能用 getCause 否则序列化时 cause 属性也可能被处理
     */
    public Throwable cause() {
        return cause;
    }


    /**
     * 判断失败原因是否为超时导致的
     */
    @SuppressWarnings("unchecked")
    public boolean timeout() {
        return ExceptionUtil.isCausedBy(cause(), SocketTimeoutException.class);
    }


    public long startTime() {
        return startTime;
    }


    public long endTime() {
        return endTime;
    }


    public long interval() {
        return interval;
    }
}
